package com.example.easybuy.service;

import com.example.easybuy.entity.User;
import com.example.easybuy.util.ElasticsearchUtil;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Service
public class UserService {
    
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    
    private static final String INDEX_NAME = "users";
    
    /**
     * 保存用户到Elasticsearch
     *
     * @param user 用户对象
     * @return 文档ID
     * @throws IOException IO异常
     */
    public String save(User user) throws IOException {
        return elasticsearchUtil.save(INDEX_NAME, user.getId().toString(), user);
    }
    
    /**
     * 根据ID获取用户
     *
     * @param id 用户ID
     * @return 用户对象
     * @throws IOException IO异常
     */
    public User getById(Long id) throws IOException {
        Map<String, Object> source = elasticsearchUtil.getById(INDEX_NAME, id.toString());
        if (source != null) {
            User user = new User();
            user.setId(id);
            user.setLoginName((String) source.get("loginName"));
            user.setUserName((String) source.get("userName"));
            user.setPassword((String) source.get("password"));
            // 处理性别字段，可能从ES获取的是字符串
            Object sexObj = source.get("sex");
            if (sexObj instanceof Integer) {
                user.setSex((Integer) sexObj);
            } else if (sexObj instanceof String) {
                user.setSex(Integer.valueOf((String) sexObj));
            }
            
            user.setIdentityCode((String) source.get("identityCode"));
            user.setEmail((String) source.get("email"));
            user.setMobile((String) source.get("mobile"));
            
            // 处理类型字段，可能从ES获取的是字符串
            Object typeObj = source.get("type");
            if (typeObj instanceof Integer) {
                user.setType((Integer) typeObj);
            } else if (typeObj instanceof String) {
                user.setType(Integer.valueOf((String) typeObj));
            }
            return user;
        }
        return null;
    }
    
    /**
     * 更新用户信息
     *
     * @param user 用户对象
     * @return 是否更新成功
     * @throws IOException IO异常
     */
    public boolean update(User user) throws IOException {
        return elasticsearchUtil.update(INDEX_NAME, user.getId().toString(), user);
    }
    
    /**
     * 根据ID删除用户
     *
     * @param id 用户ID
     * @return 是否删除成功
     * @throws IOException IO异常
     */
    public boolean deleteById(Long id) throws IOException {
        return elasticsearchUtil.deleteById(INDEX_NAME, id.toString());
    }
    
    /**
     * 获取所有用户
     *
     * @return 用户列表
     * @throws IOException IO异常
     */
    public List<User> getAllUsers() throws IOException {
        SearchResponse response = elasticsearchUtil.searchAll(INDEX_NAME);
        List<User> users = new ArrayList<>();
        
        for (SearchHit hit : response.getHits().getHits()) {
            Map<String, Object> source = hit.getSourceAsMap();
            User user = new User();
            user.setId(Long.valueOf(hit.getId()));
            user.setLoginName((String) source.get("loginName"));
            user.setUserName((String) source.get("userName"));
            user.setPassword((String) source.get("password"));
            // 处理性别字段，可能从ES获取的是字符串
            Object sexObj = source.get("sex");
            if (sexObj instanceof Integer) {
                user.setSex((Integer) sexObj);
            } else if (sexObj instanceof String) {
                user.setSex(Integer.valueOf((String) sexObj));
            }
            
            user.setIdentityCode((String) source.get("identityCode"));
            user.setEmail((String) source.get("email"));
            user.setMobile((String) source.get("mobile"));
            
            // 处理类型字段，可能从ES获取的是字符串
            Object typeObj = source.get("type");
            if (typeObj instanceof Integer) {
                user.setType((Integer) typeObj);
            } else if (typeObj instanceof String) {
                user.setType(Integer.valueOf((String) typeObj));
            }
            users.add(user);
        }
        
        return users;
    }
    
    /**
     * 创建用户索引
     *
     * @return 是否创建成功
     * @throws IOException IO异常
     */
    public boolean createIndex() throws IOException {
        return elasticsearchUtil.createIndex(INDEX_NAME);
    }
}